/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * 迭代实现
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {
    if(!root)return [];
    let res = [],
        cur = root,
        pre = null;

    while (cur){
        if(!cur.left){
            res.push(cur.val);
            cur = cur.right;
        }else{
            pre = cur.left;
            while (pre.right && pre.right!==cur){
                pre = pre.right;
            }
            if(!pre.right){
                pre.right = cur;
                cur = cur.left;
            }else if(pre.right===cur){
                pre.right = null;
                res.push(cur.val);
                cur = cur.right;
            }

        }
    }
    return res;
};